package com.example.project.projectspringcloud.service;

import com.example.project.projectspringcloud.dao.BaseMapper;
import com.example.project.projectspringcloud.entity.BaseEntity;
import com.example.project.projectspringcloud.entity.Page;
import com.example.project.projectspringcloud.utils.WebUtil;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;

/**
 * 公共基础Service, 包含 get, list, save, delete 公用方法
 *
 * @param <T>
 * @param <Mapper>
 */
public abstract class BaseService<T extends BaseEntity, Mapper extends BaseMapper<T>> {

    @Autowired
    protected Mapper mapper;

    /**
     * get single by condition
     * ==============================================================================
     *
     * @param t
     * @return
     */
    protected T get(T t) {
        return mapper.selectOne(t);
    }

    /**
     * get list by condition
     * ==============================================================================
     *
     * @param page
     * @param t
     * @return
     */
    protected List<T> list(Page page, T t) {
        if (page != null) {
            PageHelper.startPage(page.getPageNum(), page.getPageSize());
        }

        return mapper.selectAll(t);
    }

    /**
     * insert/update by BaseEntity.newRecord Selective Type
     * ==============================================================================
     *
     * @param t
     * @return
     */
    protected boolean save(T t) {
        if (t.isNewRecord()) {
            if (t.getCreateDate() == null) {
                t.setCreateDate(new Date());
            }
            t.setCreateUser(WebUtil.getCurrentUser().getId());
            return mapper.insertSelective(t) > 0;
        } else {
            t.setUpdateDate(new Date());
            t.setUpdateUser(WebUtil.getCurrentUser().getId());
            return mapper.updateByPrimaryKeySelective(t) > 0;
        }
    }

    /**
     * insert/update by Absolute
     * ==============================================================================
     *
     * @param t
     * @return
     */
    protected boolean saveAbsolute(T t) {
        if (t.isNewRecord()) {
            t.setCreateDate(new Date());
            t.setCreateUser(WebUtil.getCurrentUser().getId());
            return mapper.insert(t) > 0;
        } else {
            t.setUpdateDate(new Date());
            t.setUpdateUser(WebUtil.getCurrentUser().getId());
            return mapper.updateByPrimaryKey(t) > 0;
        }
    }

    /**
     * delete by array ids
     * ==============================================================================
     *
     * @param ids
     * @return
     */
    protected boolean delete(Integer[] ids) {

        return mapper.deleteByArrayPrimaryKey(ids) > 0;
    }
}
